package com.njbw.train.gateway.filter;

import com.njbw.train.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {

    // Mono 是事件编程/响应式编程的一个类
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 排除不需要拦截的请求
        if (path.contains("/admin")
            || path.contains("/member/member/login")
            || path.contains("/member/member/register")
            || path.contains("/member/member/sendCode")) {
            log.info("不需要登录验证：{}", path);
            return chain.filter(exchange);
        }

        // 需要登录验证的请求
        log.info("需要登录验证：{}", path);

        // 获取 header 的 token 参数
        String token = request.getHeaders().getFirst("token");
        log.info("会员登录验证开始，token：{}", token);
        if (StringUtils.isBlank(token)) {
            log.info("token 为空，验证不通过，请求被拦截");
            return rejectRequestWithUnAuthorized(exchange);
        }

        // 校验 token 是否有效，包括 token 是否被改过（是否能被解析），是否过期
        boolean validate = JwtUtil.validate(token);
        if (validate) {
            log.info("token 有效，放行该请求");
            return chain.filter(exchange);
        }

        return rejectRequestWithUnAuthorized(exchange);
    }

    /**
     * 由于没有权限（未认证）拒绝请求
     */
    private static Mono<Void> rejectRequestWithUnAuthorized(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 优先级设置，值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
